package com.by.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.by.entity.Category;
import com.by.result.Result;
import com.by.service.CategoryService;
import com.by.vo.CategoryTreeVo;
import com.by.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询分类树
     */
    @GetMapping("/tree")
    public Result<List<CategoryTreeVo>> selectCategoryTreeNestedResult() {
        List<CategoryTreeVo> page = categoryService.selectCategoryTree(0L);
        return Result.success(page);
    }

    /**
     * 根据id查询分类信息
     */
    @GetMapping("/detail")
    public Result<Category> getCategoryDetail(@RequestParam("id") Long id) {
        Category category = categoryService.getById(id);
        return Result.success(category);
    }
    /**
     * 添加分类（包含一级分类和子类）
     */
     @PostMapping("/save")
    public Result<Boolean> saveCategory(@RequestBody CategoryVo categoryVo) {
         Category category = new Category();
         BeanUtils.copyProperties(categoryVo, category);
         //添加层级
         Category byId = categoryService.getById(categoryVo.getParentCid());
         if (byId == null) {
            return Result.error(400, "上级分类不存在");
        }
         category.setCatLevel(byId.getCatLevel() + 1);
         boolean result = categoryService.saveOrUpdate(category);
        return Result.success(result);
    }
    /**
     * 修改分类
     */
    @PostMapping("/update")
    public Result<Boolean> updateCategory(@RequestBody CategoryVo CategoryVo) {
        Long catId = CategoryVo.getCatId();
        // 1. 判断分类是否存在
        Category category = categoryService.getById(catId);
        if (category == null) {
            return Result.error(400, "分类不存在");
        }
        BeanUtils.copyProperties(CategoryVo, category);
        boolean result = categoryService.saveOrUpdate(category);
        return Result.success(result);
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/delete")
    public Result<Boolean> deleteCategory(@RequestParam("id") Long id) {
        // 1. 判断分类是否存在
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error(400, "分类不存在");
        }

        // 2. 判断是否有子分类
        int childrenCount = (int) categoryService.count(new QueryWrapper<Category>().eq("parent_cid", id));
        if (childrenCount > 0) {
            return Result.error(400, "该分类下有子分类，不能删除");
        }

        // 3. 执行删除
        boolean result = categoryService.removeById(id);
        return Result.success(result);
    }
}
